package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.tanhua.dubbo.utils.Idworker;
import com.tanhua.model.domain.Video;
import com.tanhua.model.vo.PageResultVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/7 23:00
 */

@DubboService
public class VideoApiImpl implements VideoApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private Idworker idworker;

    /**
     * 发布小视频
     * @param video
     * @return
     */
    @Override
    public String save(Video video) {
        //1、设置属性
        video.setVid(idworker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        //2、调用方法保存对象
        mongoTemplate.save(video);
        //3、返回对象id
        return video.getId().toHexString();
    }

    /**
     * 根据vid查询数据列表
     * @param vids
     * @return
     */
    @Override
    public List<Video> findMovementsByVids(List<Long> vids) {


        Criteria criteria = Criteria.where("vid").in(vids);
        Query query = Query.query(criteria);
        List<Video> videos = mongoTemplate.find(query, Video.class);
        return videos;
    }

    /**
     * 分页查询数据
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Video> queryVideoList(int page, Integer pagesize) {

        Query query = new Query()
                .limit(pagesize)
                .skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> videos = mongoTemplate.find(query, Video.class);
        return videos;
    }

    @Override
    public PageResultVo findByUserId(Integer page, Integer pagesize, Long uid) {

        Query query = Query.query(Criteria.where("userId").in(uid));
        long count = mongoTemplate.count(query, Video.class);
        // 分页查询
        query.limit(pagesize).skip((page - 1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> videos = mongoTemplate.find(query, Video.class);
        PageResultVo vo = new PageResultVo(page, pagesize, (int) count, videos);
        return vo;
    }
}
